package shark.flow.identity.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.idm.api.Group;
import org.flowable.idm.engine.impl.GroupQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import shark.user.spi.entity.SysRole;
import shark.user.spi.mapper.SysRoleMapper;
import shark.user.spi.mapper.SysUserRoleMapper;

import java.util.ArrayList;
import java.util.List;

public class SharkGroupQueryImpl extends GroupQueryImpl {

    private SysRoleMapper sysRoleMapper;

    public SharkGroupQueryImpl() {}

    public SharkGroupQueryImpl(SysRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
    }

    @Override
    public long executeCount(CommandContext commandContext) {
        return executeQuery().size();
    }

    @Override
    public List<Group> executeList(CommandContext commandContext) {
        return executeQuery();
    }

    protected List<Group> executeQuery() {
        if (getUserId() != null) {
            return findGroupsByUser(getUserId());
        } else if (getId() != null) {
            return findGroupsById(getId());
        } else {
            return findAllGroups();
        }
    }

    protected List<Group> findGroupsByUser(String userId) {
        List<Group> groups = new ArrayList<>();
        List<SysRole> roles = sysRoleMapper.getRolesByUserId(userId);
        for (SysRole role : roles) {
            GroupEntityImpl groupEntity = new GroupEntityImpl();
            groupEntity.setId(role.getId());
            groupEntity.setName(role.getRoleCode());
            groupEntity.setType(role.getRoleName());
            groups.add(groupEntity);
        }

        return groups;
    }

    protected List<Group> findGroupsById(String id) {
        List<Group> groups = new ArrayList<>();
        SysRole sysRole = sysRoleMapper.selectById(id);
        if (sysRole == null) {
            return groups;
        }
        GroupEntityImpl groupEntity = new GroupEntityImpl();
        groupEntity.setId(sysRole.getId());
        groupEntity.setName(sysRole.getRoleCode());
        groupEntity.setType(sysRole.getRoleName());
        groups.add(groupEntity);
        return groups;

    }

    protected List<Group> findAllGroups() {
        List<Group> groups = new ArrayList<>();
        List<SysRole> roles = sysRoleMapper.selectList(new QueryWrapper<>());
        for (SysRole role : roles) {
            GroupEntityImpl groupEntity = new GroupEntityImpl();
            groupEntity.setId(role.getId());
            groupEntity.setName(role.getRoleCode());
            groupEntity.setType(role.getRoleName());
            groups.add(groupEntity);
        }
        return groups;
    }
}
